//
//  YKStatusCacheTool.m
//  youkan
//
//  Created by 吴高烽 on 16/4/10.
//  Copyright © 2016年 Honsintech. All rights reserved.
//

#import "YKStatusCacheTool.h"
#import "FMDB.h"
#import "YKWBStatues.h"
#import "YKAccount.h"
#import "YKAccountTool.h"
#import "YKStatusParam.h"
@implementation YKStatusCacheTool
static  FMDatabase *_db;
// 类方法创建表
+(void)initialize{
    
    NSString *cachePath =NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath=[cachePath stringByAppendingString:@"status.sqlite"];
    _db =[FMDatabase databaseWithPath:filePath];
    if ([_db open]) { //打开成功 创建表格
        YKLog(@"缓存数据库打开成功");
    }else{
        YKLog(@"缓存数据库打开失败");
    }
    BOOL flag =   [_db executeUpdate:@"create table if not exists t_status (id integer primary key autoincrement,idstr text,access_token text,dict blob);"];
    if (flag) {
        YKLog(@"创建成功");
    }else{
        YKLog(@"创建失败");
    }
}
// 存数据
+(void)saveWithStatus:(NSArray *)status{

    for (NSDictionary *sta in status) {
        NSString *idstr =sta[@"idstr"];
        NSString *accseeToken =[YKAccountTool account].access_token;
//        NSDictionary *statusDict =sta.keyValues;
//        YKLog(@"%@",statusDict);
        NSData *data =[NSKeyedArchiver archivedDataWithRootObject:sta];
        BOOL flag =   [_db executeUpdate:@"insert into t_status(idstr,access_token,dict) values(?,?,?)",idstr,accseeToken,data];
        if (flag) {
            YKLog(@"插入成功");
        }else{
            YKLog(@"插入失败");
        }
    }
}
// 取数据,根据条件查询
+(NSArray *)statusesWithParam:(YKStatusParam *)param{

    NSString *sql =[NSString stringWithFormat:@"select * from t_status where access_token = '%@' order by idstr desc limit 20;",param.access_token];
    if (param.since_id) {// 获取最新微博的查询语句
        sql =[NSString stringWithFormat:@"select * from t_status where access_token = '%@' and idstr >'%@' order by idstr desc limit 20;",param.access_token,param.since_id];
    }else if (param.max_id){ //获取更多微博的查询语句
        sql =[NSString stringWithFormat:@"select * from t_status where access_token = '%@' and idstr<='%@' order by idstr desc limit 20;",param.access_token,param.max_id];
    }
    FMResultSet *set =[_db executeQuery:sql];
    NSMutableArray *mArr=[NSMutableArray array];
    while ([set next]) {// 将取出的数据转成模型存在数组中
        NSData *data =[set dataNoCopyForColumn:@"dict"];
        NSDictionary *dic= [NSKeyedUnarchiver unarchiveObjectWithData:data];
        YKWBStatues *statue=[YKWBStatues objectWithKeyValues:dic];
        [mArr addObject:statue];
    }
    return mArr;
}
@end
